import DetailsRecord from '@/pages/publicity/components/record/DetailsRecord';
import { overallPanel, overallPanelPublicityPage } from '@/services/api/api-analysis';
import ProCard from '@ant-design/pro-card';
import ProList from '@ant-design/pro-list';
import { ActionType } from '@ant-design/pro-table';
import { each, groupBy } from '@antv/util';
import { Cascader, DatePicker, Space, Statistic, Tag, Typography } from 'antd';
import Paragraph from 'antd/lib/typography/Paragraph';
import moment from 'moment';
import { useEffect, useRef, useState } from 'react';

interface OverallPanelCardProps {
  selectOrganization: any
}

const OverallPanelCard: React.FC<OverallPanelCardProps> = (props) => {
  const { selectOrganization } = props

  const monthFormat = 'YYYY-MM-DD';
  const startDate = moment().startOf('month');
  const endOfDate = moment();

  const actionRef = useRef<ActionType>();
  const [ellipsis, setEllipsis] = useState(true);
  /**
   * 初始收录数据
   */
  const [dataOverallPanel, setDataOverallPanelState] = useState<AnalysisData.OverallPanel>();
  //日期范围
  const [dataDates, setDataDatesState] = useState<string[]>([startDate.format(monthFormat), endOfDate.format(monthFormat)])

  //七日内刊播趋势数据
  const [overallPanelCardcolumnData, setOverallPanelCardcolumnDataState] = useState()


  const sourceTopIdOptions = [
    {
      value: '',
      label: '全部',
    },
    {
      value: '7275100000010000',
      label: '新闻传播工作质效',
    },
    {
      value: '7275100000020000',
      label: '媒情网情社情转交办事项回复质效',
    },
    {
      value: '7275100000030000',
      label: '文化繁荣质效',
    },
    {
      value: '7275100000040000',
      label: '文化遗产保护质效',
    },
  ]

  //选择组织类型
  const [dataSourceTopName, setDataSourceTopNameState] = useState<string>(sourceTopIdOptions[0].label);
  const [dataSourceTopId, setDataSourceTopIdState] = useState<string>(sourceTopIdOptions[0].value);

  /**
   * 加载收录数据
   * @param key
   */
  const loadOverallPanelData = async () => {
    try {
      const response = await overallPanel({ organizationId: selectOrganization.id, dates: dataDates });
      if (response.code === 0) {
        setDataOverallPanelState(response.data);
      }
    } catch (error) { }
  };

  /**
   * 恢复默认
   */
  useEffect(() => {
    loadOverallPanelData();
    actionRef?.current?.reset();
  }, [selectOrganization, dataDates, dataSourceTopId]);

  const [data, setData] = useState([]);

  const asyncFetch = () => {
    fetch('https://gw.alipayobjects.com/os/antfincdn/8elHX%26irfq/stack-column-data.json')
      .then((response) => response.json())
      .then((json) => {
        setData(json), console.log(json);
      })
      .catch((error) => {
        console.log('fetch data failed', error);
      });
  };
  // 也可以在项目中直接使用 lodash
  const annotations = [];
  each(groupBy(data, 'year'), (values, k) => {
    const value = values.reduce((a, b) => a + b.value, 0);
    annotations.push({
      type: 'text',
      position: [k, value],
      content: `${value}`,
      style: {
        textAlign: 'center',
        fontSize: 14,
        fill: 'rgba(0,0,0,0.85)',
      },
      offsetY: -10,
    });
  });


  const config = {
    data,
    isStack: true,
    xField: 'year',
    yField: 'value',
    seriesField: 'type',
    label: {
      // 可手动配置 label 数据标签位置
      position: 'middle',
      // 'top', 'bottom', 'middle'
      // 可配置附加的布局方法
      layout: [
        // 柱形图数据标签位置自动调整
        {
          type: 'interval-adjust-position',
        }, // 数据标签防遮挡
        {
          type: 'interval-hide-overlap',
        }, // 数据标签文颜色自动调整
        {
          type: 'adjust-color',
        },
      ],
    },
    // 使用 annotation （图形标注）来展示：总数的 label
    annotations,
  };



  /**
   * 请求网络
   * @param value
   */
  const request = async (params = {}) => {
    const response = await overallPanelPublicityPage({ ...params, organizationId: selectOrganization.id, dates: dataDates, sourceTopId: dataSourceTopId });

    return Promise.resolve({
      data: response.data.data,
      total: response.data.total,
      success: response.code === 0,
    });
  };


  return (
    <ProCard
      headerBordered
      bordered={false}
      extra={<DatePicker.RangePicker
        allowClear={false}
        defaultValue={[startDate, endOfDate]}
        format={monthFormat}
        disabledDate={(current) => {
          return current && current > moment().endOf('day')
        }}
        onChange={(values, dates) => {
          setDataDatesState(dates)
        }}
        ranges={{
          今日: [moment(), moment()],
          本月: [moment().startOf('month'), moment().endOf('month')],
          上月: [
            moment().startOf('month').subtract(1, 'months'),
            moment().endOf('month').subtract(1, 'months'),
          ],
          最近7天: [moment().subtract(6, 'days'), moment()],
          最近60天: [moment().subtract(59, 'days'), moment()],
          最近90天: [moment().subtract(89, 'days'), moment()],
        }}
      />}

      colSpan={{ xs: 24, sm: 22, md: 22, lg: 22, xl: 22 }}
    >
      <ProCard split="horizontal" bordered>
        {dataOverallPanel && <ProCard split="horizontal" >
          <ProCard split="vertical" >
            <ProCard title="线索报送（篇）" >
              <Statistic value={dataOverallPanel?.cuesTotalAdopt} suffix={<>
                <span style={{
                  fontSize: 10
                }}>收录</span>
                <>{`/ ${dataOverallPanel?.cuesTotal}`}</>
                <span style={{
                  fontSize: 10
                }}>提交</span>
              </>} />
            </ProCard>
            <ProCard title="线索征集（篇）" >
              <Statistic value={dataOverallPanel?.cuesCountSubmitAdopt} suffix={<>
                <span style={{
                  fontSize: 10
                }}>收录</span>
                <>{`/ ${dataOverallPanel?.cuesCountSubmit}`}</>
                <span style={{
                  fontSize: 10
                }}>提交</span>
              </>} />
            </ProCard>
            <ProCard title="主动报送（篇）" >
              <Statistic value={dataOverallPanel?.cuesCountActiveAdopt} suffix={<>
                <span style={{
                  fontSize: 10
                }}>收录</span>
                <>{`/ ${dataOverallPanel?.cuesCountActive}`}</>
                <span style={{
                  fontSize: 10
                }}>提交</span>
              </>} />
            </ProCard>
          </ProCard>
          <ProCard split="vertical">
            <ProCard >
              <div style={{ display: 'flex', flexDirection: "column", justifyContent: 'space-between', height: 80 }}>
                <div>宣传刊播</div>
                <Statistic value={dataOverallPanel?.publicityTotal} suffix={<>
                  <span style={{
                    fontSize: 10
                  }}>篇</span>
                  <>{`/ ${dataOverallPanel?.publicityTotalScore}`}</>
                  <span style={{
                    fontSize: 10
                  }}>分</span>
                </>} />
              </div>
            </ProCard>
            <ProCard>
              <div style={{ display: 'flex', flexDirection: "column", justifyContent: 'space-between', height: 80 }}>
                <div>中央媒体</div>
                <Statistic value={dataOverallPanel?.publicityCountZYMT} suffix={<>
                  <span style={{
                    fontSize: 10
                  }}>篇</span>
                  <>{`/ ${dataOverallPanel?.publicityCountZYMTScore}`}</>
                  <span style={{
                    fontSize: 10
                  }}>分</span>
                </>} />
              </div>
            </ProCard>
            <ProCard>
              <div style={{ display: 'flex', flexDirection: "column", justifyContent: 'space-between', height: 80 }}>
                <div>市/区县级媒体</div>
                <Statistic value={dataOverallPanel?.publicityCountSQXMT} suffix={<>
                  <span style={{
                    fontSize: 10
                  }}>篇</span>
                  <>{`/ ${dataOverallPanel?.publicityCountSQXMTScore}`}</>
                  <span style={{
                    fontSize: 10
                  }}>分</span>
                </>} />
              </div>
            </ProCard>
            <ProCard>
              <div style={{ display: 'flex', flexDirection: "column", justifyContent: 'space-between', height: 80 }}>
                <div>文化推广</div>
                <Statistic value={dataOverallPanel?.publicityCountWHTG} suffix={<>
                  <span style={{
                    fontSize: 10
                  }}>篇</span>
                  <>{`/ ${dataOverallPanel?.publicityCountWHTGScore}`}</>
                  <span style={{
                    fontSize: 10
                  }}>分</span>
                </>} />
              </div>
            </ProCard>
            <ProCard>
              <div style={{ display: 'flex', flexDirection: "column", justifyContent: 'space-between', height: 80 }}>
                <div>新闻发布会</div>
                <Statistic value={dataOverallPanel?.publicityCountXWFBH} suffix={<>
                  <span style={{
                    fontSize: 10
                  }}>篇</span>
                  <>{`/ ${dataOverallPanel?.publicityCountXWFBHScore}`}</>
                  <span style={{
                    fontSize: 10
                  }}>分</span>
                </>} />
              </div>
            </ProCard>
            {/* <ProCard title="中央媒体" ><Statistic value={dataOverallPanel?.publicityCountZYMT} suffix={`篇 / ${dataOverallPanel?.publicityCountZYMTScore}分`} /></ProCard>
            <ProCard title="市/区县级媒体" ><Statistic value={dataOverallPanel?.publicityCountSQXMT} suffix={`篇 / ${dataOverallPanel?.publicityCountSQXMTScore}分`} /></ProCard>
            <ProCard title="对外传播" ><Statistic value={dataOverallPanel?.publicityCountDWCB} suffix={`篇 / ${dataOverallPanel?.publicityCountDWCBScore}分`} /></ProCard> */}
          </ProCard>
          <ProCard split="vertical">
            <ProCard  >
              <div style={{ display: 'flex', flexDirection: "column", justifyContent: 'space-between', height: 105 }}>
                <div>媒情网情社情转交办事项回复情况</div>
                <Statistic value={dataOverallPanel?.publicityCountMQWQSQZJBSXHFQK} suffix={<>
                  <span style={{
                    fontSize: 10
                  }}>篇</span>
                  <>{`/ ${dataOverallPanel?.publicityCountMQWQSQZJBSXHFQKScore}`}</>
                  <span style={{
                    fontSize: 10
                  }}>分</span>
                </>} />
              </div>
            </ProCard>
            <ProCard>
              <div style={{ display: 'flex', flexDirection: "column", justifyContent: 'space-between', height: 105 }}>
                <div>评价文艺创作获奖</div>
                <Statistic value={dataOverallPanel?.publicityCountPJWYCZHJ} style={{ marginTop: 25 }} suffix={<>
                  <span style={{
                    fontSize: 10
                  }}>篇</span>
                  <>{`/ ${dataOverallPanel?.publicityCountPJWYCZHJScore}`}</>
                  <span style={{
                    fontSize: 10
                  }}>分</span>
                </>} />
              </div>
            </ProCard>
            <ProCard>
              <div style={{ display: 'flex', flexDirection: "column", justifyContent: 'space-between', height: 105 }}>
                <div>承办或参加展演展播</div>
                <Statistic value={dataOverallPanel?.publicityCountCBHCJZYZB} suffix={<>
                  <span style={{
                    fontSize: 10
                  }}>篇</span>
                  <>{`/ ${dataOverallPanel?.publicityCountCBHCJZYZBScore}`}</>
                  <span style={{
                    fontSize: 10
                  }}>分</span>
                </>} />
              </div>
            </ProCard>
            <ProCard>
              <div style={{ display: 'flex', flexDirection: "column", justifyContent: 'space-between', height: 105 }}>
                <div>文化遗产保护传承整体效能</div>
                <Statistic value={dataOverallPanel?.publicityCountWHYCBHCCZTXN} suffix={<>
                  <span style={{
                    fontSize: 10
                  }}>篇</span>
                  <>{`/ ${dataOverallPanel?.publicityCountWHYCBHCCZTXNScore}`}</>
                  <span style={{
                    fontSize: 10
                  }}>分</span>
                </>} />
              </div>
            </ProCard>
            <ProCard>
              <div style={{ display: 'flex', flexDirection: "column", justifyContent: 'space-between', height: 105 }}>
                <div>博物馆服务效能</div>
                <Statistic value={dataOverallPanel?.publicityCountBWGFWXN} suffix={<>
                  <span style={{
                    fontSize: 10,
                  }}>篇</span>
                  <>{`/ ${dataOverallPanel?.publicityCountBWGFWXNScore}`}</>
                  <span style={{
                    fontSize: 10
                  }}>分</span>

                </>} />
              </div>
            </ProCard>
            <ProCard >
              <div style={{ display: 'flex', flexDirection: "column", justifyContent: 'space-between', height: 105 }}>
                <div>区县级文物“四有”及文物巡查</div>
                <Statistic value={dataOverallPanel?.publicityCountQXJWWSYJWWXC} suffix={<>
                  <span style={{
                    fontSize: 10
                  }}>篇</span>
                  <>{`/ ${dataOverallPanel?.publicityCountQXJWWSYJWWXCScore}`}</>
                  <span style={{
                    fontSize: 10
                  }}>分</span>
                </>} />
              </div>
            </ProCard>
          </ProCard>
        </ProCard>}
        <ProCard ghost>
          <ProList<AnalysisData.OverallPanelPublicity>
            style={{ paddingLeft: 24, paddingRight: 24 }}
            headerTitle={<span >宣传刊播列表</span>}
            toolBarRender={() => [
              <span style={{ marginRight: 20 }}>
                &nbsp;
                <Cascader defaultValue={[dataSourceTopId]} options={sourceTopIdOptions} onChange={(value: any[], selectOptions: any) => {
                  setDataSourceTopIdState(value[value.length - 1]);
                  setDataSourceTopNameState(selectOptions.map((item: { label: any; }) => item.label).join(' > '))
                }}
                ><a>{dataSourceTopName}</a></Cascader>
              </span>
            ]}
            ghost
            grid={{ gutter: 16, column: 2 }}
            actionRef={actionRef}
            pagination={{
              defaultPageSize: 4,
              showSizeChanger: true,
              pageSizeOptions: [4, 8, 12, 16]
            }}
            request={request}
            onRow={(row, index) => {
              return {
                onClick: (event) => {
                }, // 点击行
                onDoubleClick: (event) => { },
                onContextMenu: (event) => { },
                onMouseEnter: (event) => { }, // 鼠标移入行
                onMouseLeave: (event) => { },
              };
            }}
            rowKey="id"
            metas={{
              content: {
                render: (text, row, index, action) => {
                  return (
                    <>
                      <div style={{ display: 'flex', flexDirection: 'column', justifyContent: 'space-between', height: '60px' }}>
                        <div >
                          <Paragraph ellipsis={ellipsis ? { rows: 2 } : false}>
                            {row.title}
                          </Paragraph>
                        </div>
                        <div style={{ position: 'absolute', bottom: '10px' }}>
                          <span>{moment(row.publishTime).format('YYYY-MM-DD')}</span>
                        </div>
                      </div>
                    </>)
                }
              },
              actions: {
                render: (text, row, index, action) => (
                  // <span>{moment(row.publishTime).format('yyyy-MM-DD')}</span>
                  // <a key="run">更多

                  // </a>
                  <DetailsRecord id={row.id} name={'更多'} onRefurbish={() => { }} />
                ),
              },
              title: {
                render(text, row, index, action) {
                  return (
                    <>
                      <div style={{ maxWidth: 460 }}>
                        <Space>
                          <Tag color={row.sourceTopName == "中央媒体" ? "red" : row.sourceTopName == "市/区县级媒体" ? "green" : "blue"}>{row.sourceTopName}</Tag>
                          {row.sourceNames.slice(0, 3).map((item) => (
                            <Tag key={item}>{item}</Tag>
                          ))}
                        </Space>
                        <div style={{
                          marginTop: "10px"
                        }}>
                          关联单位：
                          <Space>
                            {row.participateOrganizationNames.slice(0, 4).map((item) => (
                              <Tag key={item}>{item}</Tag>
                            ))}
                          </Space>
                        </div>
                      </div>
                    </>
                  )
                },
              }
            }}
          />
        </ProCard>
        {/* <ProCard title="七日内刊播趋势">
          <Column
            height={390}
            data={data}
            isStack={true}
            xField="year"
            yField="value"
            seriesField="type"
            label={{
              // 可手动配置 label 数据标签位置
              position: 'middle',
              // 'top', 'bottom', 'middle'
              // 可配置附加的布局方法
              layout: [
                // 柱形图数据标签位置自动调整
                {
                  type: 'interval-adjust-position',
                }, // 数据标签防遮挡
                {
                  type: 'interval-hide-overlap',
                }, // 数据标签文颜色自动调整
                {
                  type: 'adjust-color',
                },
              ],
            }}
          />
        </ProCard> */}
      </ProCard>
      {/* <ProCard split="horizontal">
      <ProCard
        title="收录来源占用情况"
        bodyStyle={{
          padding: 0,
        }}
      >
        <Pie
          autoFit={true}
          appendPadding={10}
          data={[
            {
              x: '中央媒体',
              y: 12,
            },
            {
              x: '市属媒体',
              y: 12,
            },
            {
              x: '区县媒体',
              y: 12,
            },
            {
              x: '市外媒体',
              y: 56,
            },
            {
              x: '其他',
              y: 56,
            },
          ]}
          radius={0.5}
          innerRadius={0.64}
          height={300}
          angleField="y"
          colorField="x"
          legend={false}
          label={{
            type: 'spider',
            formatter: (text, item) => {
              // eslint-disable-next-line no-underscore-dangle
              return `${item._origin.x}: ${item._origin.y}`;
            },
          }}
          statistic={{
            title: {
              content: '总量',
            },
          }}
        />
      </ProCard>
      <ProCard
        title="收录渠道占用情况"
        bodyStyle={{
          padding: 0,
        }}
      >
        <Pie
          autoFit={true}
          appendPadding={10}
          data={[
            {
              x: '抖音',
              y: 12,
            },
            {
              x: '微信',
              y: 12,
            },
            {
              x: '电子报',
              y: 12,
            },
            {
              x: '其他',
              y: 56,
            },
          ]}
          radius={0.5}
          innerRadius={0.64}
          height={300}
          angleField="y"
          colorField="x"
          legend={false}
          label={{
            type: 'spider',
            formatter: (text, item) => {
              // eslint-disable-next-line no-underscore-dangle
              return `${item._origin.x}: ${item._origin.y}`;
            },
          }}
          statistic={{
            title: {
              content: '总量',
            },
          }}
        />
      </ProCard>
    </ProCard> */}
    </ProCard>
  );
};

export default OverallPanelCard;
